package br.org.underserver.resposta;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import br.org.underserver.resquisicao.Request;
import org.wsl.controle.Controlador;

/**
 * Resposta utilizada para testes do servidor
 * 
 * @author Thiago Galbiatti Vespa - <a
 *         href="mailto:thiago@thiagovespa.com.br">thiago@thiagovespa.com.br</a>
 * @version 1.0
 *
 */
public class DummyResponse implements Response {

	private Request request;

	protected static final DateFormat HTTP_DATE_FORMAT = new SimpleDateFormat(
			"EEE, dd MMM yyyy HH:mm:ss z");

	/**
	 * Construtor do Dummy Response
	 * @param request requisição para análise da resposta
	 */
	public DummyResponse(Request request) {
		this.request = request;
	}

	@Override
	public String respond() {
		StringBuilder sb = new StringBuilder();
		// Cria primeira linha do status code, no caso sempre 200 OK
		sb.append("HTTP/1.1 200 OK").append("\r\n");
		
		// Cria os cabeçalhos
		sb.append("Date: ").append(HTTP_DATE_FORMAT.format(new Date())).append("\r\n");
		sb.append("Server: Test Server - http://www.alex.query.com.br").append("\r\n");
		sb.append("Connection: Close").append("\r\n");
		//sb.append("Content-Type: text/html; charset=UTF-8").append("\r\n");
                
                //System.out.println("url:"+this.request.getUri());
                
                if(this.request.getUri().contains("crossdomain.xml")){
                    sb.append("Content-Type: application/xml; charset=UTF-8").append("\r\n");
                    sb.append("\r\n"); 
                    sb.append("<?xml version=\"1.0\"?>");
                    sb.append("<cross-domain-policy>");
                    sb.append("<allow-access-from domain=\"*\" to-ports=\"*\"/>");
                    sb.append("</cross-domain-policy>");
                }else if(this.request.getUri().contains("?")){
                    sb.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
                    sb.append("\r\n"); 
                    int idRequest = 158;
                    try{                
                       idRequest = Integer.parseInt(this.request.getParameters().get("idRequest")[0]);
                    }catch(Exception e){                
                    }                       
                    try {
                          Controlador.getInstancia().deployWS(this.request.getParameters());
                    } catch (Exception e) {
                       //Controlador.getInstancia().addErro(e.getMessage().toString());	
                    }   
                    sb.append(Controlador.getInstancia().getResult(idRequest));
                }else{
                    sb.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
                    sb.append("\r\n"); 
                    sb.append("null"); 
                }
                //System.out.println(sb.toString());
		return sb.toString();

	}

}
